package de.kimera.view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.EventObject;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.table.DatePickerCellEditor;

import de.kimera.api.IEmail;
import de.kimera.api.IEmployee;
import de.kimera.api.IShift;
import de.kimera.controller.Controller;
import de.kimera.controller.EmailManager;
import de.kimera.model.Email;
import de.kimera.model.Shift;
import de.kimera.utils.Utils;

public class ApplicationFrame extends JFrame {

	private JPanel contentPane;
	private JTextField pfadTextField;
	private JTable dienstTable;
	private JComboBox comboBox;
	private JLabel firstNameDataLabel;
	private JLabel birthDateData;
	private JLabel lastNameData;
	private JLabel addressData;
	private JLabel dienstNameData;
	private JLabel emailData;
	private JButton changeDataButton;
	private JButton createReportButton;
	private JButton sendEmailButton;
	private JLabel infoLabel;
	private JButton selectButton;
	private JButton removeRowButton;
	private JButton addRowButton;
	
	//need to be public static because of the popup windows
	//TODO: remove if it is not necessary anymore
	public static JFrame frame;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frame = new ApplicationFrame();
					//set the look and feel
					//setLookAndFeel();
					frame.setTitle(Utils.LABEL_TITLE_FRAME);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private static void setLookAndFeel(){
		LookAndFeelInfo[] lookAndFeelInfos = UIManager.getInstalledLookAndFeels();
		System.out.println("Number of installed LookAndFeels: "+lookAndFeelInfos.length);		
		String selectedLookAndFeel = lookAndFeelInfos[4].getClassName();
		System.out.println("Selected LookAndFeel: "+selectedLookAndFeel);
		try {
			UIManager.setLookAndFeel(selectedLookAndFeel);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Create the frame.
	 */
	public ApplicationFrame() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(Utils.calculateBounds(Utils.MAIN_WINDOW_WIDHT,Utils.MAIN_WINDOW_HEIGHT));
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 17));
		setContentPane(contentPane);
		
		JPanel nordPanel = new JPanel();
		contentPane.add(nordPanel, BorderLayout.NORTH);
		nordPanel.setLayout(new BorderLayout(5, 0));
		
		JPanel dataPanel = new JPanel();
		nordPanel.add(dataPanel, BorderLayout.CENTER);
		dataPanel.setLayout(new GridLayout(0, 1, 0, 10));
		
		JPanel pdfPanel = new JPanel();
		dataPanel.add(pdfPanel);
		pdfPanel.setLayout(new BorderLayout(5, 0));
		
		JLabel selectPdfLabel = new JLabel(Utils.LABEL_LABEL_SELECTPDF);
		pdfPanel.add(selectPdfLabel, BorderLayout.WEST);
		selectPdfLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		pfadTextField = new JTextField();
		//TODO: remove
		//pfadTextField.setText("D:\\tamas_data\\eclipseRCP\\workspace\\KIMERA\\files\\Nachtwachen Dienstplan Mai 2012.pdf");
		pdfPanel.add(pfadTextField);
		
		pfadTextField.setFont(new Font("Tahoma", Font.PLAIN, 14));
		pfadTextField.setColumns(20);
		
		JPanel selectEmployeePanel = new JPanel();
		dataPanel.add(selectEmployeePanel);
		selectEmployeePanel.setLayout(new BorderLayout(20, 0));
		
		JLabel selectEmployeeLabel = new JLabel(Utils.LABEL_LABEL_SELECTEMPLOYEE);
		selectEmployeePanel.add(selectEmployeeLabel, BorderLayout.WEST);
		selectEmployeeLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		selectEmployeeLabel.setHorizontalAlignment(SwingConstants.LEFT);
		
		comboBox = new JComboBox();
		selectEmployeePanel.add(comboBox);
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String employeeName = (String)comboBox.getSelectedItem();
				if(employeeName==null || employeeName.isEmpty()) return;
				
				IEmployee selectedEmployee = Controller.getInstance().getEmployee(employeeName);
				
				showEmployeeData(selectedEmployee);
				
				List<IShift> shifts = Controller.getInstance().getShifts(employeeName);
				loadShiftsIntoTheTable(shifts);
				
				enableButtons();			
			}
		});
		((JLabel)comboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
		
		JPanel buttonsPanelNord = new JPanel();
		nordPanel.add(buttonsPanelNord, BorderLayout.EAST);
		buttonsPanelNord.setPreferredSize(new Dimension(Utils.BUTTONSPANEL_WIDHT,5));
		buttonsPanelNord.setLayout(new GridLayout(0, 1, 0, 10));
		
		selectButton = new JButton(Utils.LABEL_BUTTON_SELECTPDF);
		selectButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (pfadTextField.getText().isEmpty()) {

					// show File Chooser Dialog
					JFileChooser fileChooser = new JFileChooser(".");
					// filter only pdf files
					fileChooser.addChoosableFileFilter(new FileFilter() {

						@Override
						public boolean accept(File f) {
							if (f.isDirectory()) {
								return true;
							}

							String extension = Utils.getExtension(f);
							if (extension != null) {
								return extension.equals("pdf");
							}

							return false;
						}

						@Override
						public String getDescription() {
							return "*.pdf";
						}

					});
					int returnVal = fileChooser.showOpenDialog(ApplicationFrame.this);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						File selectedFile = fileChooser.getSelectedFile();
						pfadTextField.setText(selectedFile.getAbsolutePath());
					} else {
						return;
					}

				}

				// load the pdf document from the file
				Controller.getInstance().loadPDFDocument(pfadTextField.getText());

				// show Service Data
				String serviceDate = Controller.getInstance().getServiceDateString();
				infoLabel.setText(Utils.LABEL_LABEL_INFO + "          " + serviceDate);

				// remove all obsolete values from the comboBox
				comboBox.removeAllItems();
				// load the new values
				List<String> employeeNames = Controller.getInstance().getEmployeeNames();
				for (String employeeName : employeeNames)
					comboBox.addItem(employeeName);

			}
		});
		buttonsPanelNord.add(selectButton);
		selectButton.setIcon(new ImageIcon(ApplicationFrame.class.getResource("/de/kimera/view/icons/folder.png")));
		
		JLabel lblNewLabel_1 = new JLabel("");
		buttonsPanelNord.add(lblNewLabel_1);
		
		JPanel centerPanel = new JPanel();
		centerPanel.setBorder(null);
		contentPane.add(centerPanel, BorderLayout.CENTER);
		centerPanel.setLayout(new BorderLayout(5, 0));
		
		infoLabel = new JLabel(Utils.LABEL_LABEL_INFO);
		infoLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		infoLabel.setHorizontalAlignment(SwingConstants.LEFT);
		centerPanel.add(infoLabel, BorderLayout.NORTH);
		
		dienstTable = new JTable(){
			@Override
			public TableCellEditor getCellEditor(int row, int column) {
				if(column == 0){
					DatePickerCellEditor datePickerCellEditor = new DatePickerCellEditor();
					datePickerCellEditor.setFormats(new SimpleDateFormat(Utils.DATE_FORMAT));
					datePickerCellEditor.setClickCountToStart(1);
					return datePickerCellEditor;
				}else{
					return new DefaultCellEditor(new JTextField());
				}
			}
		};
		dienstTable.setCellSelectionEnabled(true);
		dienstTable.setFont(new Font("Tahoma", Font.PLAIN, 14));
		dienstTable.setBorder(null);
		dienstTable.setModel(new DefaultTableModel(
			new Object[][] {},
			new String[] {
				Utils.LABEL_TABLECOLUMN_DATE, Utils.LABEL_TABLECOLUMN_FROM, Utils.LABEL_TABLECOLUMN_TO
			}
		));
				
		//set the row height of the dienstTable
		dienstTable.setRowHeight(26);
		
		//center the header and the columns horizontally
		((DefaultTableCellRenderer) dienstTable.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
		
		for(int i=0;i<dienstTable.getColumnCount();i++){
			TableColumn col = dienstTable.getColumnModel().getColumn(i);
			if(i==0){
				col.setCellRenderer(new TableCellRenderer(){

					@Override
					public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
							boolean hasFocus, int row, int column) {
						String output = "";
						try{
							output =  Utils.convertDateToString((Date)value, Utils.DATE_FORMAT);
						}catch(Exception e){}
					
						JLabel label = new JLabel(output);
						label.setFont(new Font("Tahoma", Font.PLAIN, 14));
						label.setHorizontalAlignment(SwingConstants.CENTER);
						return label;
					}});
			}else{
				DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();    
        		dtcr.setHorizontalAlignment(SwingConstants.CENTER);  
        		col.setCellRenderer(dtcr);
        	}  
			
        }
				
		centerPanel.add(new JScrollPane(dienstTable), BorderLayout.CENTER);
				
		JPanel buttonsPanelCenter = new JPanel();
		centerPanel.add(buttonsPanelCenter, BorderLayout.EAST);
		buttonsPanelCenter.setPreferredSize(new Dimension(Utils.BUTTONSPANEL_WIDHT,5));
		buttonsPanelCenter.setLayout(new GridLayout(0, 1, 0, 30));
		
		JLabel lblNewLabel = new JLabel("");
		buttonsPanelCenter.add(lblNewLabel);
		addRowButton = new JButton(Utils.LABEL_BUTTON_ADDROW);
		addRowButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				addRowToTable(null,null,null);
			}
		});
		buttonsPanelCenter.add(addRowButton);
		addRowButton.setIcon(new ImageIcon(ApplicationFrame.class.getResource("/de/kimera/view/icons/addElement.png")));
		
		removeRowButton = new JButton(Utils.LABEL_BUTTON_REMOVEROW);
		removeRowButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DefaultTableModel defaultTableModel = (DefaultTableModel)dienstTable.getModel();
				int numberOfRows = defaultTableModel.getRowCount();
				
				//if there is a row selected remove that row
				if(dienstTable.getSelectedRow()!=-1){
					defaultTableModel.removeRow(dienstTable.getSelectedRow());
				}else //remove the last row if it exists
				if(numberOfRows>0)
					defaultTableModel.removeRow(numberOfRows-1);
			}
		});
		buttonsPanelCenter.add(removeRowButton);
		removeRowButton.setIcon(new ImageIcon(ApplicationFrame.class.getResource("/de/kimera/view/icons/removeElement.png")));
		
		JLabel lblNewLabel_2 = new JLabel("");
		buttonsPanelCenter.add(lblNewLabel_2);
		
		JPanel southPanel = new JPanel();
		contentPane.add(southPanel, BorderLayout.SOUTH);
		southPanel.setLayout(new BorderLayout(5, 0));
		
		JPanel userDataPanel = new JPanel();
		userDataPanel.setBorder(new TitledBorder(null, Utils.LABEL_TITLE_USERPANEL, TitledBorder.LEADING, TitledBorder.TOP, null, null));
		southPanel.add(userDataPanel, BorderLayout.CENTER);
		GridBagLayout gbl_userDataPanel = new GridBagLayout();
		gbl_userDataPanel.columnWidths = new int[]{117, 117, 117, 117, 0};
		gbl_userDataPanel.rowHeights = new int[]{18, 18, 18, 0};
		gbl_userDataPanel.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		gbl_userDataPanel.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
		userDataPanel.setLayout(gbl_userDataPanel);
		
		JLabel firstNameLabel = new JLabel(Utils.LABEL_EMPLOYEE_FIRSTNAME);
		GridBagConstraints gbc_firstNameLabel = new GridBagConstraints();
		gbc_firstNameLabel.fill = GridBagConstraints.BOTH;
		gbc_firstNameLabel.insets = new Insets(0, 10, 5, 5);
		gbc_firstNameLabel.gridx = 0;
		gbc_firstNameLabel.gridy = 0;
		userDataPanel.add(firstNameLabel, gbc_firstNameLabel);
		
		firstNameDataLabel = new JLabel();
		GridBagConstraints gbc_firstNameDataLabel = new GridBagConstraints();
		gbc_firstNameDataLabel.anchor = GridBagConstraints.WEST;
		gbc_firstNameDataLabel.fill = GridBagConstraints.VERTICAL;
		gbc_firstNameDataLabel.insets = new Insets(0, 0, 5, 5);
		gbc_firstNameDataLabel.gridx = 1;
		gbc_firstNameDataLabel.gridy = 0;
		userDataPanel.add(firstNameDataLabel, gbc_firstNameDataLabel);
		
		JLabel birthDateLabel = new JLabel(Utils.LABEL_EMPLOYEE_BIRTHDATE);
		GridBagConstraints gbc_birthDateLabel = new GridBagConstraints();
		gbc_birthDateLabel.fill = GridBagConstraints.BOTH;
		gbc_birthDateLabel.insets = new Insets(0, 0, 5, 5);
		gbc_birthDateLabel.gridx = 2;
		gbc_birthDateLabel.gridy = 0;
		userDataPanel.add(birthDateLabel, gbc_birthDateLabel);
		
		birthDateData = new JLabel();
		GridBagConstraints gbc_birthDateData = new GridBagConstraints();
		gbc_birthDateData.anchor = GridBagConstraints.EAST;
		gbc_birthDateData.gridwidth = 2;
		gbc_birthDateData.fill = GridBagConstraints.VERTICAL;
		gbc_birthDateData.insets = new Insets(0, 0, 5, 10);
		gbc_birthDateData.gridx = 2;
		gbc_birthDateData.gridy = 0;
		userDataPanel.add(birthDateData, gbc_birthDateData);
		
		JLabel lastNameLabel = new JLabel(Utils.LABEL_EMPLOYEE_LASTNAME);
		GridBagConstraints gbc_lastNameLabel = new GridBagConstraints();
		gbc_lastNameLabel.fill = GridBagConstraints.BOTH;
		gbc_lastNameLabel.insets = new Insets(0, 10, 5, 5);
		gbc_lastNameLabel.gridx = 0;
		gbc_lastNameLabel.gridy = 1;
		userDataPanel.add(lastNameLabel, gbc_lastNameLabel);
		
		lastNameData = new JLabel();
		GridBagConstraints gbc_lastNameData = new GridBagConstraints();
		gbc_lastNameData.anchor = GridBagConstraints.WEST;
		gbc_lastNameData.fill = GridBagConstraints.VERTICAL;
		gbc_lastNameData.insets = new Insets(0, 0, 5, 5);
		gbc_lastNameData.gridx = 1;
		gbc_lastNameData.gridy = 1;
		userDataPanel.add(lastNameData, gbc_lastNameData);
		
		JLabel addressLabel = new JLabel(Utils.LABEL_EMPLOYEE_ADDRESS);
		GridBagConstraints gbc_addressLabel = new GridBagConstraints();
		gbc_addressLabel.fill = GridBagConstraints.BOTH;
		gbc_addressLabel.gridx = 2;
		gbc_addressLabel.gridy = 1;
		userDataPanel.add(addressLabel, gbc_addressLabel);
		
		addressData = new JLabel();
		GridBagConstraints gbc_addressData = new GridBagConstraints();
		gbc_addressData.anchor = GridBagConstraints.EAST;
		gbc_addressData.gridwidth = 2;
		gbc_addressData.fill = GridBagConstraints.VERTICAL;
		gbc_addressData.insets = new Insets(0, 0, 5, 10);
		gbc_addressData.gridx = 2;
		gbc_addressData.gridy = 1;
		userDataPanel.add(addressData, gbc_addressData);
		
		JLabel dienstNameLabel = new JLabel(Utils.LABEL_EMPLOYEE_SERVICENAME);
		GridBagConstraints gbc_dienstNameLabel = new GridBagConstraints();
		gbc_dienstNameLabel.fill = GridBagConstraints.BOTH;
		gbc_dienstNameLabel.insets = new Insets(0, 10, 0, 5);
		gbc_dienstNameLabel.gridx = 0;
		gbc_dienstNameLabel.gridy = 2;
		userDataPanel.add(dienstNameLabel, gbc_dienstNameLabel);
		
		dienstNameData = new JLabel();
		GridBagConstraints gbc_dienstNameData = new GridBagConstraints();
		gbc_dienstNameData.anchor = GridBagConstraints.WEST;
		gbc_dienstNameData.fill = GridBagConstraints.VERTICAL;
		gbc_dienstNameData.insets = new Insets(0, 0, 0, 5);
		gbc_dienstNameData.gridx = 1;
		gbc_dienstNameData.gridy = 2;
		userDataPanel.add(dienstNameData, gbc_dienstNameData);
		
		JLabel emailLabel = new JLabel(Utils.LABEL_EMPLOYEE_EMAIL);
		GridBagConstraints gbc_emailLabel = new GridBagConstraints();
		gbc_emailLabel.fill = GridBagConstraints.BOTH;
		gbc_emailLabel.insets = new Insets(0, 0, 0, 5);
		gbc_emailLabel.gridx = 2;
		gbc_emailLabel.gridy = 2;
		userDataPanel.add(emailLabel, gbc_emailLabel);
		
		emailData = new JLabel();
		GridBagConstraints gbc_emailData = new GridBagConstraints();
		gbc_emailData.insets = new Insets(0, 0, 0, 10);
		gbc_emailData.anchor = GridBagConstraints.EAST;
		gbc_emailData.gridwidth = 2;
		gbc_emailData.fill = GridBagConstraints.VERTICAL;
		gbc_emailData.gridx = 2;
		gbc_emailData.gridy = 2;
		userDataPanel.add(emailData, gbc_emailData);
		
		JPanel buttonsPanelSouth = new JPanel();
		southPanel.add(buttonsPanelSouth, BorderLayout.EAST);
		buttonsPanelSouth.setPreferredSize(new Dimension(Utils.BUTTONSPANEL_WIDHT,5));
		buttonsPanelSouth.setLayout(new GridLayout(0, 1, 0, 3));
		
		changeDataButton = new JButton(Utils.LABEL_BUTTON_CHANGEDATA);
		changeDataButton.setEnabled(false);
		changeDataButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ChangeEmployeeDataDialog dialog = new ChangeEmployeeDataDialog();
				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
				
				IEmployee employee = Controller.getInstance().getEmployee((String)comboBox.getSelectedItem());
				dialog.setEmployee(employee);
				dialog.setVisible(true);
				
				if(dialog.isEmployeeHasBeenChanged()){
					Controller.getInstance().storeEmployeeData(employee);
					showEmployeeData(employee);
				}
			}
		});
		buttonsPanelSouth.add(changeDataButton);
		changeDataButton.setIcon(new ImageIcon(ApplicationFrame.class.getResource("/de/kimera/view/icons/edit.png")));
		
		createReportButton = new JButton(Utils.LABEL_BUTTON_CREATEREPORT);
		createReportButton.setEnabled(false);
		createReportButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				createReport();
			}
		});
		buttonsPanelSouth.add(createReportButton);
		createReportButton.setIcon(new ImageIcon(ApplicationFrame.class.getResource("/de/kimera/view/icons/pdf.png")));
		
		sendEmailButton = new JButton(Utils.LABEL_BUTTON_SENDEMAIL);
		sendEmailButton.setEnabled(false);
		sendEmailButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				IEmployee selectedEmployee = Controller.getInstance().getEmployee((String)comboBox.getSelectedItem());
										
				IEmail email = new Email();
				email.setFrom(selectedEmployee.getEmailAddress());
				
				//TODO: remove
				email.setFrom(Utils.EMAIL_DEFAULT_FROM);
				email.setPassword(Utils.EMAIL_DEFAULT_PASSWORD);
				
				String text = email.getText();
				text += selectedEmployee.getFirstName()+" "+selectedEmployee.getLastName(); //add signature to the text
				email.setText(text);
				
				Controller.getInstance().sendEmail(email);
			}
		});
		buttonsPanelSouth.add(sendEmailButton);
		sendEmailButton.setIcon(new ImageIcon(ApplicationFrame.class.getResource("/de/kimera/view/icons/envelope.png")));
	
		assignNamesToUIElements();//for test purpose
	}

	protected void createReport() {
		String employeeName = (String)comboBox.getSelectedItem();
		//parse the table and get all the shifts included there
		List<IShift> shifts = new LinkedList<IShift>();
		DefaultTableModel defaultTableModel = (DefaultTableModel)dienstTable.getModel();
		
		@SuppressWarnings("unchecked")
		Vector<Vector> rows = defaultTableModel.getDataVector();
		
		for(Vector row : rows){
			Date date = 			(Date) row.elementAt(0);
			String dateString      = Utils.convertDateToString(date,Utils.DATE_FORMAT); 
			String beginningString = (String)row.elementAt(1);
			String endString       = (String)row.elementAt(2);
			
			try{
				Date beginning = getBeginningDate(dateString, beginningString);
				boolean isAnotherDay = isAnotherDay(beginningString,endString);
				Date end 		= getEndDate(beginning, isAnotherDay, endString);
				shifts.add(new Shift(beginning, end));
			}catch(Exception e){
				//TODO: add error checking here
			}
		}
		
		
		Controller.getInstance().generatePDFReport(employeeName,shifts);
	}

	private Date getBeginningDate(String dateString,String beginningString) throws Exception{
		SimpleDateFormat formatter = new SimpleDateFormat(Utils.DATE_FORMAT);
        Date date =  formatter.parse(dateString);
                
        int beginningHour   = Integer.parseInt(beginningString.substring(0,beginningString.indexOf(":")));
        int beginningMinute = Integer.parseInt(beginningString.substring(beginningString.indexOf(":")+1));
                
        Calendar calendar = (Calendar)Calendar.getInstance().clone();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, beginningHour);
        calendar.set(Calendar.MINUTE, beginningMinute);
        
        Date returnDate = calendar.getTime(); 
        return returnDate;
	}
	
	private Date getEndDate(Date beginningDate,boolean isAnotherDay, String endString) throws Exception{
		int endHour   = Integer.parseInt(endString.substring(0,endString.indexOf(":")));
        int endMinute = Integer.parseInt(endString.substring(endString.indexOf(":")+1));
               
        Calendar calendar = (Calendar)Calendar.getInstance().clone();
        calendar.setTime(beginningDate);
        
        if(isAnotherDay){
        	calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        
        calendar.set(Calendar.HOUR_OF_DAY, endHour);
        calendar.set(Calendar.MINUTE, endMinute);
        return calendar.getTime();
	}

	/**
	 * @return true if the end of the shift is another day than the beginning
	 */
	private boolean isAnotherDay(String beginningString,String endString){
		int beginningHour   = Integer.parseInt(beginningString.substring(0,beginningString.indexOf(":")));
		int endHour   = Integer.parseInt(endString.substring(0,endString.indexOf(":")));
		return beginningHour > endHour;
	}
	
	private void loadShiftsIntoTheTable(List<IShift> shifts) {
		DefaultTableModel defaultTableModel = (DefaultTableModel)dienstTable.getModel();
		
		//remove all row from the table
		int numberOfRows = defaultTableModel.getRowCount();
		for(int i=0;i<numberOfRows;i++){
			//remove always the first row as long as there are some
			defaultTableModel.removeRow(0);
		}
		
		for(IShift shift : shifts){
			String dateString = shift.getDateString();
			String beginningString = shift.getBeginnString();
			String endString = shift.getEndString();
			addRowToTable(dateString,beginningString,endString);
		}
		
		/**fill the rest with empty lines*/
		/*numberOfRows = defaultTableModel.getRowCount();
		for(int i=numberOfRows;i<8;i++){
			defaultTableModel.addRow(new Object[]{null,null,null});
		}*/
	}

	private void addRowToTable(String dateString,String beginningString,String endString){
		Date date = null;
		if(dateString!=null){
			date = Utils.convertStringToDate(dateString, Utils.DATE_FORMAT);
		}
		
		Object[] rowData = new Object[]{date,beginningString,endString};
		DefaultTableModel defaultTableModel = (DefaultTableModel)dienstTable.getModel();
		defaultTableModel.addRow(rowData);
		
	}
	
	private void enableButtons() {
		//enable Buttons
		changeDataButton.setEnabled(true);
		createReportButton.setEnabled(true);
		sendEmailButton.setEnabled(true);		
	}

	private void showEmployeeData(IEmployee selectedEmployee) {
		firstNameDataLabel.setText(selectedEmployee.getFirstName());
		birthDateData.setText(selectedEmployee.getBirthDateString());
		lastNameData.setText(selectedEmployee.getLastName());
		addressData.setText(selectedEmployee.getAddress());
		dienstNameData.setText(selectedEmployee.getServiceName());
		emailData.setText(selectedEmployee.getEmailAddress());
	}
	
	//for test purpose
	private void assignNamesToUIElements() {
		selectButton.setName(Utils.LABEL_BUTTON_SELECTPDF);
		addRowButton.setName(Utils.LABEL_BUTTON_ADDROW);
		removeRowButton.setName(Utils.LABEL_BUTTON_REMOVEROW);
		changeDataButton.setName(Utils.LABEL_BUTTON_CHANGEDATA);
		createReportButton.setName(Utils.LABEL_BUTTON_CREATEREPORT);
		sendEmailButton.setName(Utils.LABEL_BUTTON_SENDEMAIL);
	}
}
